package com.ltxtiyu.video.tool;

import com.alibaba.fastjson.JSONObject;
import com.ltxtiyu.video.common.CodeTypeConstant;
import com.ltxtiyu.video.common.SecurityConstant;
import com.ltxtiyu.video.tool.push.push.AndroidNotification;
import com.ltxtiyu.video.tool.push.push.PushClient;
import com.ltxtiyu.video.tool.push.push.android.AndroidListcast;
import com.ltxtiyu.video.tool.push.push.android.AndroidUnicast;
import com.ltxtiyu.video.tool.push.push.ios.IOSListcast;
import com.ltxtiyu.video.tool.push.push.ios.IOSUnicast;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;


/**
 * 友盟 app消息推送
 * 如需其他推送方式,请参考友盟sdk
 *
 * 微信模板信息推送
 * access_token必须查找数据库再传参数,因为会半小时定时恒信access_token
 */
public class PushTool {
    private static PushClient client = new PushClient();
    private static final Logger LOGGER = LoggerFactory.getLogger(PushTool.class);

    /**
     * 安卓推送消息 单个
     * @param fields
     * @param deviceToken
     * @param content
     * @param fields
     * @return
     * @throws Exception
     */
    public static boolean sendAndroidUnicast(String deviceToken, String content, Map<String, String> fields) throws Exception {
        AndroidUnicast unicast = new AndroidUnicast(SecurityConstant.APPKEY_ANDROID,SecurityConstant.APPSECRET_ANDROID);
        // TODO Set your device token
        if(StringUtils.isBlank(deviceToken)){
            return false;
        }
        unicast.setDeviceToken(deviceToken);
        unicast.setTicker( "篮同学");
        unicast.setTitle("篮同学");
        unicast.setText(content);
        unicast.goCustomAfterOpen("");   // 点击推送消息到app特定页面
        unicast.setDisplayType(AndroidNotification.DisplayType.NOTIFICATION);
        // TODO Set 'production_mode' to 'false' if it's a test device.
        // For how to register a test device, please see the developer doc.
        unicast.setProductionMode();
        // Set customized fields
        // 自定义字段
        Set<String> keys = fields.keySet();
        for (String key : keys){
            String value = fields.get(key);
            if(StringUtils.isNotBlank(value)){
                unicast.setExtraField(key,value);
            }
        }
        return client.send(unicast);
    }

    /**
     * ios推送消息  单个
     * @param deviceToken
     * @param content
     * @param fields
     * @return
     * @throws Exception
     */
    public static boolean sendIOSUnicast(String deviceToken, String content, Map<String, String> fields) throws Exception {
        IOSUnicast unicast = new IOSUnicast(SecurityConstant.APPKEY_IOS,SecurityConstant.APPSECRET_IOS);
        // TODO Set your device token
        if(StringUtils.isBlank(deviceToken)){
            return false;
        }
        unicast.setDeviceToken(deviceToken);
        unicast.setAlert(content);
        unicast.setBadge(0);
        unicast.setSound("default");
        // TODO set 'production_mode' to 'true' if your app is under production mode
        /**                   注意
         *              ios测试用testMode
         *              ios正式用productionMode
         **/
//        unicast.setTestMode();          // 测试
        unicast.setProductionMode();    // 正式
        // Set customized fields
        // 自定义字段
        Set<String> keys = fields.keySet();
        for (String key : keys){
            String value = fields.get(key);
            if(StringUtils.isNotBlank(value)){
                unicast.setCustomizedField(key,value);
            }
        }
        return client.send(unicast);
    }

    /**
     * 安卓列推消息 多个
     * @param fields
     * @param deviceTokens
     * @param content
     * @param fields
     * @return
     * @throws Exception
     */
    public static boolean sendAndroidListcast(String deviceTokens, String content, Map<String, String> fields) throws Exception {
        AndroidListcast listcast = new AndroidListcast(SecurityConstant.APPKEY_ANDROID,SecurityConstant.APPSECRET_ANDROID);
        // TODO Set your device token
        if(StringUtils.isBlank(deviceTokens)){
            return false;
        }
        listcast.setDeviceTokens(deviceTokens);
        listcast.setTicker( "篮同学短视频");
        listcast.setTitle("篮同学短视频");
        listcast.setText(content);
        listcast.goCustomAfterOpen("");   // 点击推送消息到app特定页面
        listcast.setDisplayType(AndroidNotification.DisplayType.NOTIFICATION);
        // TODO Set 'production_mode' to 'false' if it's a test device.
        // For how to register a test device, please see the developer doc.
        listcast.setProductionMode();
        // Set customized fields
        // 自定义字段
        Set<String> keys = fields.keySet();
        for (String key : keys){
            String value = fields.get(key);
            if(StringUtils.isNotBlank(value)){
                listcast.setExtraField(key,value);
            }
        }
        return client.send(listcast);
    }

    /**
     * ios列推消息  多个
     * @param deviceTokens
     * @param content
     * @param fields
     * @return
     * @throws Exception
     */
    public static boolean sendIOSListcast(String deviceTokens, String content, Map<String, String> fields) throws Exception {
        IOSListcast listcast = new IOSListcast(SecurityConstant.APPKEY_IOS,SecurityConstant.APPSECRET_IOS);
        // TODO Set your device token
        if(StringUtils.isBlank(deviceTokens)){
            return false;
        }
        listcast.setDeviceTokens(deviceTokens);
        listcast.setAlert(content);
        listcast.setBadge(0);
        listcast.setSound("default");
        // TODO set 'production_mode' to 'true' if your app is under production mode
        /**                   注意
         *              ios测试用testMode
         *              ios正式用productionMode
         **/
        listcast.setTestMode();          // 测试
//        listcast.setProductionMode();    // 正式
        // Set customized fields
        // 自定义字段
        Set<String> keys = fields.keySet();
        for (String key : keys){
            String value = fields.get(key);
            if(StringUtils.isNotBlank(value)){
                listcast.setCustomizedField(key,value);
            }
        }
        return client.send(listcast);
    }


    /**
     * 微信发送模板消息
     * 模板参数格式严格按照
     * @param map
     * @param openId
     * @param url
     * @param accessToken
     * @param templateId
     * @return
     */
    public static String sendWxMessage(Map<String,String> map,String openId,String url,String accessToken,String templateId){
        // 移除map中的openid, 模板消息内容格式
        map.remove("openId");
        map.remove("url");
        // 封装data的json
        JSONObject data = new JSONObject();
        for(String key:map.keySet()){
            JSONObject body = new JSONObject();
            body.put("value",map.get(key));
            body.put("color", "#173177");
            data.put(key,body);
        }
        // 封装模板json
        JSONObject finalData = new JSONObject();
        finalData.put("data", data);
        finalData.put("touser",openId);
        finalData.put("url",url);
        finalData.put("template_id", templateId);
        // 返回结果
        String s= ApiTool.httpsRequest("URL"+accessToken,"POST",finalData.toString()).toString();
        System.out.println(s);
        return s;
    }

    public static void main(String[] args) {
        long start = new Date().getTime();
        for(int i = 0; i<305; i++){
            // 微信
            /*String s = PushTool.sendWxMomentMsg("hello",
                    CodeTypeConstant.WX_TEMPLATE_THEME_501,
                    "2020-2-1",
                    "点击查看动态信息",
                    "oI4yO1pSRrmZRGSulYTzc5Aezr34",
                    "https://www.baidu.com",
                    "14_Nx_URMGIqCaeaiCGmEmc6vw62ps6rfcfO_Xi94evwq02ivvDeL8oJtPLiN71NXI50NoWHeN-Spnc4jj38mQZMc8LL5p3ZlAksz2FngucjaG05ggnbU0lfOzkb7_LJJ3X5HLuOo08_KuvpTboVLLcAJANDD");
            System.out.println(s);*/
            // app
            try {
                Map<String, String> fields = new HashMap<>();
                fields.put("afterOpenType", String.valueOf(400));
                fields.put("momentId",String.valueOf(233));
                fields.put("mediaType",String.valueOf(101));
                PushTool.sendAndroidListcast(
                        "Al-mJKJOHhgKwqeKuLPO62Scp6y-MyfVZhQv6kRwZa_m," +
                                "AjxHvDeM-inPdX3dvUntacF3yNwTk15vW8t9OA8TKDyy",
                        "hello test!",
                        fields
                );
                // 推送ios
                /*PushTool.sendIOSListcast(
                        "f7ab30cd6c1e576470bb4275a376bbc2ad1004af59cd055aab50ed7e56ea4f16," +
                                "b81fe7679a9bedd26af4e4290ff810c35b6657a143b3736280b25512eef96d85",
                        "hello test!",
                        fields
                );*/
            } catch (Exception e) {
                LOGGER.info(">>>>>>>>>>>>>>>>app推送消息失败!");
                e.printStackTrace();
            }
            System.out.println(i);
        }
        long end = new Date().getTime();
        System.out.println(">>>>>>>>>>>>>>>>>>>用时 " + (end-start) +" 毫秒");
    }
}
